package com.quan.mall.web.controller;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.TemplateExportParams;
import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.quan.commons.core.bean.R;
import com.quan.commons.core.biz.support.MyBaseController;
import com.quan.commons.core.utils.DateUtils;
import com.quan.commons.core.utils.PageUtils;
import com.quan.commons.core.utils.WebUtils;
import com.quan.commons.log.annotation.SysLog;
import com.quan.mall.commons.export.ExportOmsOrderVo;
import com.quan.mall.commons.vo.OmsOrderVo;
import com.quan.mall.entity.OmsOrder;
import com.quan.mall.entity.OmsOrderGoods;
import com.quan.mall.service.OmsOrderService;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;


/**
 * 订单
 * @author yhaoquan
 * @email yhaoquan@163.com
 * @date 2021-03-09 17:22:37
 */
@Slf4j
@Api(tags = "订单")
@RestController
@RequestMapping("/mall/omsorder")
public class OmsOrderController extends MyBaseController {

    @Autowired
    private OmsOrderService service;

    /**
     * 保存
     * @param vo
     * @return
     */
    @SysLog("保存")
    @PostMapping("save")
    public R save(@Valid @RequestBody OmsOrderVo vo) {
        this.service.save(vo);
        return R.ok();
    }

    /**
     * 修改
     * @param vo
     * @return
     */
    @SysLog("修改")
    @PostMapping("update")
    public R update(@Valid @RequestBody OmsOrderVo vo) {
        this.service.updateById(vo);
        return R.ok();
    }

    /**
     * 删除
     * @param ids
     * @return
     */
    @SysLog("删除")
    @PostMapping("delete")
    public R delete(@RequestBody Long[] ids) {
        if (null != ids && ids.length > 0) {
            this.service.removeByIds(Arrays.asList(ids));
            return R.ok();
        } else {
            return R.failure();
        }
    }

    /**
     * 多条件查询信息详情
     * @param vo
     * @return
     */
    @SysLog("查询详情")
    @GetMapping("/info")
    public R info(OmsOrderVo vo) {
        QueryWrapper<OmsOrder> queryWrapper = new QueryWrapper<OmsOrder>(vo);
        OmsOrder omsOrder = this.service.getOne(queryWrapper);
        return R.ok().put("data", omsOrder);
    }

    /**
     * 根据ID查询信息详情
     * @param {id}
     * @return
     */
    @SysLog("查询详情")
    @GetMapping("/info/{id}")
    public R info(@PathVariable("id") Long id) {
        OmsOrder omsOrder = this.service.getById(id);
        return R.ok().put("data", omsOrder);
    }

    /**
     * 列表查询
     * @param vo
     * @return
     */
    @SysLog("查询列表")
    @GetMapping(value = "list")
    public Object list(OmsOrderVo vo) {
        List<OmsOrderVo> list = this.service.queryList(new PageUtils(request), vo);
        return R.ok().put("data", list);
    }

    /**
     * 分页查询
     * @param vo
     * @return
     */
    @SysLog("分页查询")
    @GetMapping(value = "page")
    public R queryPage(OmsOrderVo vo) {
        PageUtils page = this.service.queryPage(new PageUtils(request), vo);
        return R.ok().put("data", page);
    }

    /**
     * 查询订单详情
     * @param {id}
     * @return
     */
    @SysLog("查询订单详情")
    @GetMapping("/getOrderInfo/{id}")
    public R getOrderInfo(@PathVariable("id") Long id) {
        OmsOrderVo omsOrder = this.service.getOrderInfo(id);
        return R.ok().put("data", omsOrder);
    }

    @SysLog("取消订单")
    @GetMapping("/cancelOrder")
    public R cancelOrder(OmsOrderVo vo) {
        this.service.cancelOrder(vo);
        return R.ok();
    }

    @SysLog("后台确认收货")
    @GetMapping("/confirmReceivePack")
    public R confirmReceivePack(OmsOrderVo vo) {
        this.service.confirmReceivePack(vo);
        return R.ok();
    }

    @SysLog("订单发货")
    @PostMapping("/expressDelivery")
    public R expressDelivery(@RequestBody OmsOrderVo vo) {
        this.service.expressDelivery(vo);
        return R.ok();
    }

    @SysLog("订单备注")
    @PostMapping("/remarks")
    public R remarks(@RequestBody OmsOrderVo vo) {
        this.service.remarks(vo);
        return R.ok();
    }

    @PostMapping("export")
    public void code(@RequestBody OmsOrderVo vo) throws IOException {
        QueryWrapper<OmsOrder> queryWrapper = new QueryWrapper<OmsOrder>(vo);

        List<OmsOrder> list = this.service.list(queryWrapper);

        try {
            if (null != list && !list.isEmpty()) {
                // 组装数据
                List<ExportOmsOrderVo> objList = new ArrayList<ExportOmsOrderVo>();

                for (OmsOrder order : list) {
                    ExportOmsOrderVo ee = new ExportOmsOrderVo();
                    BeanUtil.copyProperties(order, ee);

                    /**
                     * 订单状态：0->待付款，1->待发货，2->已发货，3->已完成，4->已关闭（收到关闭订单，退货退款成功，关闭后将不显示申请退款按钮）
                     */
                    if(order.getStatus() == 0) {
                        ee.setStatus("待付款");
                    } else if(order.getStatus() == 1) {
                        ee.setStatus("待发货");
                    } else if(order.getStatus() == 2) {
                        ee.setStatus("已发货");
                    } else if(order.getStatus() == 3) {
                        ee.setStatus("已完成");
                    } else if(order.getStatus() == 4) {
                        ee.setStatus("已关闭");
                    }

                    final OmsOrderVo orderInfo = this.service.getOrderInfo(order.getId());
                    StringBuffer sb = new StringBuffer();
                    for(OmsOrderGoods goods : orderInfo.getSkus()) {
                        sb.append(goods.getSpuName()).append("["+goods.getSkuName()+"]").append("   价格:").append(goods.getSkuPrice()).append("   数量:").append(goods.getSkuNum()).append("   \n");
                    }
                    ee.setSkus(sb.toString());

                    objList.add(ee);
                }

                // 设置模板
                TemplateExportParams params = new TemplateExportParams("export/order.xlsx", true);

                // 模板数据
                Map<String, Object> map = new HashMap<String, Object>();
                map.put("now", DateUtils.getDate());
                map.put("list", objList);

                // 导出
                Workbook workbook = ExcelExportUtil.exportExcel(params, map);
                // 文件名称
                String filename = "保美池订单" + new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()) + ".xlsx";
                // 客户端下载
                WebUtils.download(response, workbook, filename);
            }

        } catch (Exception e) {
        }
    }

}
